import * as Cesium from "cesium"
// 计算贝塞尔曲线点的函数
function calculateBezierPoints(
  controlPoints: Cesium.Cartesian3[],
  t: number,
): Cesium.Cartesian3 {
  const n = controlPoints.length - 1
  let result = new Cesium.Cartesian3(0, 0, 0)
  for (let i = 0; i <= n; i++) {
    const coefficient =
      binomialCoefficient(n, i) * Math.pow(1 - t, n - i) * Math.pow(t, i)
    const weightedPoint = Cesium.Cartesian3.multiplyByScalar(
      controlPoints[i],
      coefficient,
      new Cesium.Cartesian3(),
    )
    result = Cesium.Cartesian3.add(result, weightedPoint, result)
  }
  return result
}

// 计算二项式系数的函数
function binomialCoefficient(n: number, k: number): number {
  if (k === 0 || k === n) {
    return 1
  }
  return binomialCoefficient(n - 1, k - 1) + binomialCoefficient(n - 1, k)
}

// 生成贝塞尔曲线的坐标数组
export function generateBezierCurve(
  controlPoints: Cesium.Cartesian3[],
  segments: number = 50,
): Cesium.Cartesian3[] {
  const curvePoints: Cesium.Cartesian3[] = []
  for (let i = 0; i <= segments; i++) {
    const t = i / segments
    const point = calculateBezierPoints(controlPoints, t)
    curvePoints.push(point)
  }
  return curvePoints
}
